import {
  Button,
  Divider,
  FormControlLabel,
  Paper,
  Slide,
  Switch,
  Typography,
} from "@mui/material";
import { Box } from "@mui/system";
import { useQuery } from "@tanstack/react-query";
import React from "react";
import { useContext } from "react";
import { useState } from "react";
import { useEffect } from "react";
import ReactMarkdown from "react-markdown";
import { useNavigate, useParams } from "react-router-dom";
import Loading from "../../../components/loading";
import { BLOG_URL, DELETE_BLOG_URL } from "../../../constants/url";
import { getQueryFn } from "../../../query/getQueryFn";
import { TitleContext } from "../../../router";
import { okaidia } from "react-syntax-highlighter/dist/esm/styles/prism";
import remarkGfm from "remark-gfm";
import remarkToc from "remark-toc";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import rehypeRaw from "rehype-raw";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";
import { UserProContext } from "../../../App";
import useDelBlog from "../../../query/useDelBlog";
import ConfirmDialog from "../../../components/ConfirmDialog";

import { useN01SwitchStyles } from "@mui-treasury/styles/switch/n01";
import "./Detail.css";
// import { Anchor } from "antd";
import MarkNav from "markdown-navbar";

export default function BlogDetail() {
  const titleContext = useContext(TitleContext);
  const [showNav, setShowNav] = useState(true);
  useEffect(() => {
    titleContext.setnowTitle(12);
  }, []);
  const [confirm, setConfirm] = useState(false);
  const passageId = useParams(); //文章id
  const [passage, setPassage] = useState();
  const {
    isFetching: downFetching,
    isSuccess: downSuccess,
    data: downData,
  } = useQuery(
    [BLOG_URL, { params: { bid: passageId.id }, useToken: true }],
    getQueryFn
  );
  useEffect(() => {
    if (downSuccess) {
      if (downData.data.data.length == 0) {
        navigate("/student/index");
      } else setPassage(downData.data.data[0]);
    }
  }, [downSuccess]);
  const userPro = useContext(UserProContext);
  const [delId, setdelId] = useState();

  const handleCancel = () => {
    //取消删除
    setConfirm(false);
    setdelId(null);
  };
  const {
    isSuccess: delSuccess,
    isLoading: delLoading,
    mutate: delMutate,
  } = useDelBlog();
  const handleConfirm = () => {
    //确认删除函数
    setConfirm(false);
    navigate(-1);
    delMutate({ url: DELETE_BLOG_URL + delId });
  };
  const deleteBlog = (e) => {
    setConfirm(true);
    setdelId(e);
  };
  const navigate = useNavigate();
  const handleEditor = (e) => {
    //
    navigate("/student/homepage/blogeditor/" + e);
  };

  const switchStyles = useN01SwitchStyles();
  return (
    <div>
      <ConfirmDialog
        open={confirm}
        handleClose={handleCancel}
        handleConfirm={handleConfirm}
        text={"你确定要删除这篇博文吗?删除后不可恢复"}
      />
      {downFetching && <Loading />}
      {downSuccess && !downFetching && (
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            // alignItems: "center",
          }}
        >
          {/* <div className={`nav-container ${showNav ? "show" : "hide"}`}>
            <div
              className="toggle-btn"
              onClick={() => {
                setShowNav(!showNav);
                // setNavVisible(!navVisible);
              }}
            >
              {showNav ? "MENU →" : "← MENU"}
            </div>
          </div> */}

          <Paper
            elevation={4}
            sx={{
              marginLeft: "70px",
              padding: "50px 30px",
              width: "70%",
              minWidth: "800px",
            }}
          >
            <Box>
              <Typography variant="h4" sx={{ fontWeight: "bold" }}>
                {passage?.title}
              </Typography>
              <Divider sx={{ margin: "10px" }} />
              <Box
                sx={{
                  display: "flex",
                  flexDirection: "row",
                  alignItems: "center",
                }}
              >
                <Typography>posted @{passage?.time}</Typography>
                <Box sx={{ flexGrow: 1 }} />
                {passage?.name == userPro.userPro?.name && (
                  <Button color="error" onClick={() => deleteBlog(passage.id)}>
                    删除
                  </Button>
                )}
                {passage?.name == userPro.userPro?.name && (
                  <Button onClick={() => handleEditor(passage.id)}>编辑</Button>
                )}
              </Box>

              <Divider sx={{ margin: "10px" }} />
            </Box>

            <Box>
              {/* <ReactMarkdown>{passage?.content}</ReactMarkdown> */}
              <ReactMarkdown
                children={passage?.content}
                remarkPlugins={[remarkGfm, remarkToc, remarkMath]}
                rehypePlugins={[rehypeKatex]}
                escapeHtml={false}
                components={{
                  code({ node, inline, className, children, ...props }) {
                    const match = /language-(\w+)/.exec(className || "");
                    return !inline && match ? (
                      <SyntaxHighlighter
                        children={String(children).replace(/\n$/, "")}
                        style={okaidia}
                        language={match[1]}
                        PreTag="div"
                        {...props}
                      />
                    ) : (
                      <code className={className} {...props}>
                        {children}
                      </code>
                    );
                  },
                }}
              />
            </Box>
          </Paper>
          <FormControlLabel
            sx={{ zIndex: "20", position: "fixed", right: "10px" }}
            control={
              <Switch
                classes={switchStyles}
                checked={showNav}
                onChange={() => {
                  setShowNav(!showNav);
                }}
              />
            }
          />
          <Box
            sx={{
              marginTop: "50px",
              position: "fixed",
              right: "20px",
              width: "200px",
            }}
          >
            <Slide direction="left" in={showNav} mountOnEnter unmountOnExit>
              <Paper sx={{ zIndex: "20", padding: "10px 20px" }} elevation={3}>
                <Typography variant="h6" fontWeight="bold">
                  目录
                </Typography>
                <Divider sx={{ margin: "8px 0" }} />
                <MarkNav
                  onNavItemClick={null}
                  updateHashAuto={false}
                  headingTopOffset={3}
                  source={"# \n" + passage?.content}
                />
              </Paper>
            </Slide>
          </Box>
        </Box>
      )}
    </div>
  );
}
